﻿using System.Collections.Generic;
using System.Linq;
using GMap.NET;
using GMap.NET.EXT;

namespace LeakView.service
{
    class PipeModal
    {
        public static readonly PipeModal ME = new PipeModal();

        public static readonly PointLatLng default_center = new PointLatLng(39.185422, 112.252810);

        private PointLatLng center = default_center;
        public PointLatLng Center
        {
            get { return center; }
        }

        private double distance = 0.0;
        public double Distance
        {
            get { return distance; }
        }

        private List<PointLatLng> points = new List<PointLatLng>();
        public List<PointLatLng> Points
        {
            get { return points; }
        }

        public PointLatLng First
        {
            get { return Valid ? points.First() : PointLatLng.Empty; }
        }

        public PointLatLng Last
        {
            get { return Valid ? points.Last() : PointLatLng.Empty; }
        }

        public bool Valid
        {
            get { return points.Count > 0; }
        }

        public void Parse(PointLatLng first, PointLatLng last, string coordinates)
        {
            // 如果起点的位置与位置序列的第一个点不一样，而与最后一个点一样，则反转位置序列
            var gps = PointLatLngs.parse(coordinates, " ", ",");
            if(gps.Valid && !gps.First.Equals(first) && gps.First.Equals(last))
            {
                gps.Reverse();
            }

            List<PointLatLng> temp = new List<PointLatLng>();
            if (first.IsEmpty) points.Add(first);
            temp.AddRange(gps.Points);
            if (last.IsEmpty) points.Add(last);

            points.Clear();
            temp.ForEach(latlng =>
            {
                points.Add(EvilTransform.transform(latlng));
            });

            PointLatLngs pointLatLngs = PointLatLngs.at(points);

            this.center = pointLatLngs.Center;
            if (this.center.IsEmpty)
                this.center = default_center;

            this.distance = pointLatLngs.Distance;
        }

        public void Parse(string coordinates)
        {
            Parse(PointLatLng.Empty, PointLatLng.Empty, coordinates);
        }

        public PointLatLng GetPosition(double distance)
        {
            return PointLatLngs.at(points).getPositionByDistance(distance);
        }

    }

}
